#!/usr/bin/python3
# -*- coding: utf-8 -*-
from datetime import datetime
import sys
from xml.dom.minidom import parse
import os


def createFolder():
    if os.path.isdir(baseFolderPath):
        print("路径:{}，已有文件夹。程序将MD文件写入该文件夹".format(baseFolderPath))
        return True
    try:
        os.mkdir(baseFolderPath)
        print("已新建名为：" + baseFolderPath + "的文件夹")
        return True
    except Exception as e:
        print("请检查文件:", baseFolderPath)
        return False


# GMT时间转datetime
# original 就是GMT格式的时间
# gmtFormat 用来匹配GMT时间的格式，%a这些字符怎么来可以看注释1
def convertTime(original):
    gmtFormat = "%a, %d %b %Y %H:%M:%S GMT"
    # 格式化后 强制转为字符串，把':'替换为'-' 因为直接创建带':'的文件会报错
    result = str(datetime.strptime(original, gmtFormat)).replace(':', '-')
    #result.split()
    #return result

    # 标题只保留 yyyy-mm-dd
    result.split()
    return result.split()[0]

def convertTitle(original):
    # 格式化后 强制转为字符串，把':'替换为'-' 因为直接创建带':'的文件会报错
    original = original.replace('/', '、')
    original = original.replace('\\', '、')
    return original

def convertGuid(original):
    # 获取 entry name
    original = os.path.basename(original)
    original = original.split(".")[0]
    #if original.isdigit():
    #    original=""

    return original

def parserXML():
    # xml的文件名
    domTree = parse(xmlPath)
    # 文档根元素
    rootNode = domTree.documentElement
    # 所有文章
    items = rootNode.getElementsByTagName("item")
    for item in items:
        auther = item.getElementsByTagName("author")[0].childNodes[0].data
        title = item.getElementsByTagName("title")[0].childNodes[0].data
        date = item.getElementsByTagName("pubDate")[0].childNodes[0].data
        title = convertTitle(title)
        date = convertTime(date)
        # date = date[3] + '~' + date[2] + '~' + date[1]
        html = item.getElementsByTagName("guid")[0].childNodes[0].data
        html = convertGuid(html)
        content = item.getElementsByTagName("description")[0].childNodes[0].data
        mdFileName = r"{}{}：{}.md".format(baseFolderPath, date, title)
        #mdFileName = r"{}{}_{}.md".format(baseFolderPath, date, title)
        #mdFileName = r"{}{}_{}_{}.md".format(baseFolderPath, date, auther, title)
        # 如果该文件已存在，覆盖写该文件
        if os.path.exists(mdFileName):
            f = open(mdFileName, 'w+', encoding='utf-8')
        else:
            f = open(mdFileName, 'a+', encoding='utf-8')
        #print(html)
        f.write(content)
        print(mdFileName)


# 保存md文件的文件夹路径
baseFolderPath = "./parserResult1/"
# 需要解析的xml路径
xmlPathDefault = "./CNBlogs_BlogBackup.xml"
xmlPath = xmlPathDefault
if __name__ == '__main__':
    if len(sys.argv) > 0:
        xmlPath = str(sys.argv[1])

    if not createFolder():
        print("创建文件夹程序出错")
        sys.exit(-1)
    else:
        parserXML()
